import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export default async function handler(req, res) {
  if (req.method === "GET") {
    const { id } = req.query;
    if (id) {
      try {
        const user = await prisma.permission.findUnique({
          where: { id: parseInt(id) },
        });

        if (!user) {
          return res.status(404).json({ error: "用户未找到" });
        }
        return res.status(200).json(user);
      } catch (error) {
        console.log("error --- ", error);
        return res.status(500).json({ error: "获取用户失败" });
      }
    } else {
      // 查询所有用户
      const users = await prisma.permission.findMany();
      return res.status(200).json(users);
    }
  }

  if (req.method === "POST") {
    // 创建新权限
    const { name } = req.body;
    try {
      const newPermission = await prisma.permission.create({
        data: { name },
      });
      return res.status(201).json(newPermission);
    } catch (error) {
      return res.status(500).json({ error: "创建权限失败" });
    }
  }

  if (req.method === "PUT") {
    // 更新权限
    const { id } = req.query; // 从查询参数中获取 id
    const { name } = req.body;
    try {
      const updatedPermission = await prisma.permission.update({
        where: { id: parseInt(id) },
        data: { name },
      });
      return res.status(200).json(updatedPermission);
    } catch (error) {
      return res.status(500).json({ error: "更新权限失败" });
    }
  }

  if (req.method === "DELETE") {
    // 删除权限
    const { id } = req.query; // 从查询参数中获取 id
    try {
      await prisma.permission.delete({
        where: { id: parseInt(id) },
      });
      return res.status(204).end(); // No Content
    } catch (error) {
      return res.status(500).json({ error: "删除权限失败" });
    }
  }

  // 处理不支持的方法
  res.setHeader("Allow", ["GET", "POST", "PUT", "DELETE"]);
  res.status(405).end(`Method ${req.method} Not Allowed`);
}
